package com.supermap.localization.impl;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.supermap.localization.api.FileExtracter;
import com.supermap.localization.api.LocalizationOperation;
import com.supermap.localization.commontypes.SampleInfo;
import com.supermap.localization.util.ConfigsUtil;
import com.supermap.localization.util.MapUtil;
import com.supermap.localization.util.SampleInfoUtil;

public class LocalizationExtracter implements LocalizationOperation {

    private static Logger logger = Logger.getLogger(LocalizationExtracter.class);

    private FileExtracter fileExtacter;

    private Map<String, SampleInfo> sampleMap = new HashMap<>();

    private SampleSaveManager saveManager;

    public void setFileExtacter(FileExtracter fileExtacter) {
        this.fileExtacter = fileExtacter;
    }

    public void setSaveManager(SampleSaveManager saveManager) {
        this.saveManager = saveManager;
    }

    @Override
    public void execute() {
        Path srcPath = Paths.get(ConfigsUtil.extractConfig.getSourceDir());
        try {
            Files.walkFileTree(srcPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
                    try {
                        List<SampleInfo> sampleInfos = fileExtacter.extract(path);
                        MapUtil.addSampleInfoList(sampleMap, sampleInfos);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        throw new RuntimeException(e);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
            List<SampleInfo> sampleInfoList = SampleInfoUtil.sortByStringDesc(MapUtil.convertToList(sampleMap));
            saveManager.save(sampleInfoList);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        logger.info("提取样本成功！参见：" + ConfigsUtil.extractConfig.getExtractFilePath());
        System.out.println("提取样本成功！参见：" + ConfigsUtil.extractConfig.getExtractFilePath());
    }

}
